<template>
  <div class="statistics-view">
    <div class="top-header">
      <div class="page-title">
        <h2>统计分析</h2>
        <p class="subtitle">用户知识点和题目数据分析</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><Document /></el-icon>
                <span>学科总数</span>
              </div>
            </template>
            <div class="card-content" :class="{'shimmer-effect': cardLoading.subject}">
              <h3>{{ cardLoading.subject ? '··' : statistics.subjectCount }}</h3>
              <p>个学科</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><Connection /></el-icon>
                <span>知识点总数</span>
              </div>
            </template>
            <div class="card-content" :class="{'shimmer-effect': cardLoading.knowledge}">
              <h3>{{ cardLoading.knowledge ? '··' : statistics.knowledgeCount }}</h3>
              <p>个知识点</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><QuestionFilled /></el-icon>
                <span>题目总数</span>
              </div>
            </template>
            <div class="card-content" :class="{'shimmer-effect': cardLoading.question}">
              <h3>{{ cardLoading.question ? '··' : statistics.questionCount }}</h3>
              <p>道题目</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon><Files /></el-icon>
                <span>试卷总数</span>
              </div>
            </template>
            <div class="card-content" :class="{'shimmer-effect': cardLoading.paper}">
              <h3>{{ cardLoading.paper ? '··' : statistics.paperCount }}</h3>
              <p>份试卷</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <!-- 第一行图表 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>各学科知识点分布</span>
                <el-tooltip content="展示各学科知识点数量分布" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container-wrapper">
              <div v-if="chartLoading.subjectKnowledge" class="chart-skeleton pie-skeleton">
                <div class="pie-placeholder"></div>
              </div>
              <div id="subjectKnowledgeChart" class="chart-container" :class="{'invisible': chartLoading.subjectKnowledge}"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>各学科题目分布</span>
                <el-tooltip content="展示各学科题目数量分布" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container-wrapper">
              <div v-if="chartLoading.subjectQuestion" class="chart-skeleton bar-skeleton">
                <div class="bar-item" v-for="n in 5" :key="n"></div>
              </div>
              <div id="subjectQuestionChart" class="chart-container" :class="{'invisible': chartLoading.subjectQuestion}"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 第二行图表 -->
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>知识点掌握程度分布</span>
                <el-tooltip content="各掌握程度的知识点数量分布" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container-wrapper">
              <div v-if="chartLoading.masteryDistribution" class="chart-skeleton donut-skeleton">
                <div class="donut-placeholder"></div>
              </div>
              <div id="masteryDistributionChart" class="chart-container" :class="{'invisible': chartLoading.masteryDistribution}"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>知识点难度系数分布</span>
                <el-tooltip content="各难度系数的知识点数量分布" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="chart-container-wrapper">
              <div v-if="chartLoading.difficultyDistribution" class="chart-skeleton pie-skeleton">
                <div class="pie-placeholder"></div>
              </div>
              <div id="difficultyDistributionChart" class="chart-container" :class="{'invisible': chartLoading.difficultyDistribution}"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- <el-row :gutter="20" style="margin-top: 20px;"> -->
        <!-- 第三行图表 -->
        <!-- <el-col :span="24">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>知识图谱月度增长趋势</span>
                <el-tooltip content="近6个月知识点增长趋势" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div id="knowledgeGrowthChart" class="chart-container"></div>
          </el-card>
        </el-col> -->
      <!-- </el-row> -->

      <!-- 新增: 章节知识点详情 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>各学科章节知识点分布</span>
                <el-tooltip content="查看每个学科各章节知识点分布" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
                <div class="header-actions">
                  <el-select 
                    v-model="chapterSelectedSubject" 
                    placeholder="请选择学科"
                    size="small"
                    @change="handleChapterSubjectChange"
                    :disabled="loading"
                  >
                    <el-option
                      v-for="subject in chartData.subjects"
                      :key="subject"
                      :label="subject"
                      :value="subject"
                    />
                  </el-select>
                </div>
              </div>
            </template>
            <div class="chart-container-wrapper">
              <div v-if="chartLoading.chapterKnowledge" class="chart-skeleton bar-skeleton bar-skeleton-wide">
                <div class="bar-item" v-for="n in 8" :key="n"></div>
              </div>
              <div id="chapterKnowledgeChart" class="chart-container" :class="{'invisible': chartLoading.chapterKnowledge}"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 新增: 题目类型分布 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>各学科题目类型分布</span>
                <el-tooltip content="查看每个学科各类型题目数量分布" placement="top">
                  <el-icon><InfoFilled /></el-icon>
                </el-tooltip>
                <div class="header-actions">
                  <el-select 
                    v-model="questionTypeSelectedSubject" 
                    placeholder="请选择学科"
                    size="small"
                    @change="handleQuestionTypeSubjectChange"
                    :disabled="loading"
                  >
                    <el-option
                      v-for="subject in chartData.subjects"
                      :key="subject"
                      :label="subject"
                      :value="subject"
                    />
                  </el-select>
                </div>
              </div>
            </template>
            <div class="chart-container-wrapper">
              <div v-if="chartLoading.questionType" class="chart-skeleton donut-skeleton donut-skeleton-large">
                <div class="donut-placeholder"></div>
                <div class="legend-placeholder">
                  <div class="legend-item" v-for="n in 6" :key="n"></div>
                </div>
              </div>
              <div id="questionTypeChart" class="chart-container" :class="{'invisible': chartLoading.questionType}"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { getSubjects } from '@/api/subject';
import { getAllGraphData, getGraphDataBySubjectId } from '@/api/graph';
import { getPaperList } from '@/api/paper';
import { getLibrariesBySubject } from '../../api/library';
import { getLibraryQuestions } from '../../api/question';
import { 
  Document, 
  Connection, 
  QuestionFilled, 
  Files, 
  InfoFilled,
  Loading
} from '@element-plus/icons-vue';

// 加载状态
const loading = ref(true);
const cardLoading = ref({
  subject: true,
  knowledge: true,
  question: true,
  paper: true
});
const chartLoading = ref({
  subjectKnowledge: true,
  subjectQuestion: true,
  masteryDistribution: true,
  difficultyDistribution: true,
  chapterKnowledge: true,
  questionType: true
});

// 统计数据
const statistics = ref({
  subjectCount: 0,
  knowledgeCount: 0,
  questionCount: 0,
  paperCount: 0
});

// 图表实例
let subjectKnowledgeChart = null;
let subjectQuestionChart = null;
let masteryDistributionChart = null;
let difficultyDistributionChart = null;
let knowledgeGrowthChart = null;
let chapterKnowledgeChart = null;
let questionTypeChart = null;

// 图表数据
const chartData = ref({
  subjects: [],
  knowledgeBySubject: [],
  questionsBySubject: [],
  masteryDistribution: {},
  difficultyDistribution: {},
  monthlyGrowth: [],
  chapterKnowledgeData: {},
  questionTypeData: {}
});

// 选择的学科
const chapterSelectedSubject = ref('');
const questionTypeSelectedSubject = ref('');

// 初始化统计数据
const initStatistics = async () => {
  try {
    // 设置加载状态
    loading.value = true;
    Object.keys(cardLoading.value).forEach(key => {
      cardLoading.value[key] = true;
    });
    Object.keys(chartLoading.value).forEach(key => {
      chartLoading.value[key] = true;
    });

    // 获取用户ID
    const user = JSON.parse(localStorage.getItem('user'));
    const userId = user.id;

    // 获取学科列表
    const subjectsResponse = await getSubjects(userId, 1, 100);
    if (subjectsResponse.code === 200) {
      const subjects = subjectsResponse.data.list;
      statistics.value.subjectCount = subjects.length;
      chartData.value.subjects = subjects.map(item => item.name);
      
      // 学科数据加载完成
      cardLoading.value.subject = false;

      // 统计每个学科的知识点数量
      let totalKnowledgeCount = 0;
      const knowledgeBySubject = [];
      const questionsBySubject = [];

      // 掌握程度统计
      const masteryData = {
        '了解': 0,
        '理解': 0,
        '掌握': 0,
        '应用': 0,
      };

      // 难度系数统计
      const difficultyData = {
        '1': 0,
        '2': 0,
        '3': 0
      };

      // 创建月度数据数组
      const monthsData = [];
      const now = new Date();
      for (let i = 5; i >= 0; i--) {
        const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
        const monthStr = `${month.getFullYear()}-${String(month.getMonth() + 1).padStart(2, '0')}`;
        monthsData.push({
          month: monthStr,
          count: 0
        });
      }

      // 章节知识点数据
      const chapterKnowledgeData = {};
      
      // 题目类型数据
      const questionTypeData = {};

      // 获取每个学科的知识点数据
      for (const subject of subjects) {
        try {
          const graphResponse = await getGraphDataBySubjectId(subject.id);
          if (graphResponse.code === 200) {
            const knowledgePoints = graphResponse.data || [];
            totalKnowledgeCount += knowledgePoints.length;
            knowledgeBySubject.push({
              name: subject.name,
              value: knowledgePoints.length
            });

            // 统计每个掌握程度的知识点数量
            knowledgePoints.forEach(point => {
              if (point.mastery && masteryData[point.mastery] !== undefined) {
                masteryData[point.mastery]++;
              }

              if (point.difficulty && difficultyData[point.difficulty] !== undefined) {
                difficultyData[point.difficulty]++;
              }

              // 统计月度数据
              if (point.createdAt) {
                const createdDate = new Date(point.createdAt);
                const createdMonth = `${createdDate.getFullYear()}-${String(createdDate.getMonth() + 1).padStart(2, '0')}`;
                
                const monthIndex = monthsData.findIndex(m => m.month === createdMonth);
                if (monthIndex !== -1) {
                  monthsData[monthIndex].count++;
                }
              }
            });

            // 统计章节知识点数量
            const subjectChapterData = [];
            // 按章节分组统计
            const chapterGroups = {};
            knowledgePoints.forEach(point => {
              const chapter = point.chapter;
              if (!chapterGroups[chapter]) {
                chapterGroups[chapter] = [];
              }
              chapterGroups[chapter].push(point);
            });
            
            // 转换为数组格式
            Object.entries(chapterGroups).forEach(([chapter, points]) => {
              subjectChapterData.push({
                chapter,
                count: points.length
              });
            });
            
            // 排序
            subjectChapterData.sort((a, b) => a.chapter - b.chapter);
            chapterKnowledgeData[subject.name] = subjectChapterData;

            // 获取学科题库列表
            const librariesRes = await getLibrariesBySubject(subject.id, 1, 100);
            let libraries = [];
            const subjectQuestions = [];
            
            // 定义题目类型计数对象
            let questionTypes = {
              'SINGLE_CHOICE': 0,
              'MULTIPLE_CHOICE': 0,
              'TRUE_FALSE': 0,
              'FILL_BLANK': 0,
              'SHORT_ANSWER': 0,
              'READING': 0
            };
            
            // 获取该学科下所有题库的题目
            if (librariesRes.code === 200) {
              libraries = librariesRes.data.list;
              
              // 遍历每个题库，获取题目
              for (const library of libraries) {
                // console.log("librarie", library);
                const questionRes = await getLibraryQuestions(library.id);
                if (questionRes.code === 200) {
                  subjectQuestions.push(...questionRes.data);
                }
              }
              
              // console.log(subject.name + "subjectQuestions", subjectQuestions);
              
              // 统计每种题型的数量
              subjectQuestions.forEach(question => {
                // 根据题目的type字段统计
                if (question.questionType && questionTypes[question.questionType] !== undefined) {
                  questionTypes[question.questionType]++;
                }
              });
            } else {
              // 如果获取失败，使用模拟数据作为备选
              questionTypes = {
                'SINGLE_CHOICE': Math.floor(knowledgePoints.length * 0.3),
                'MULTIPLE_CHOICE': Math.floor(knowledgePoints.length * 0.25),
                'TRUE_FALSE': Math.floor(knowledgePoints.length * 0.2),
                'FILL_BLANK': Math.floor(knowledgePoints.length * 0.15),
                'SHORT_ANSWER': Math.floor(knowledgePoints.length * 0.08),
                'READING': Math.floor(knowledgePoints.length * 0.02)
              };
            }
            
            questionTypeData[subject.name] = questionTypes;
            
            // 计算题目总数
            const totalQuestions = Object.values(questionTypes).reduce((sum, count) => sum + count, 0);
            questionsBySubject.push({
              name: subject.name,
              value: totalQuestions
            });
            
            // 累计总题目数
            statistics.value.questionCount += totalQuestions;
          }
        } catch (error) {
          console.error(`获取${subject.name}知识点数据失败:`, error);
        }
      }

      // 知识点数据加载完成
      cardLoading.value.knowledge = false;
      
      // 题目数据加载完成
      cardLoading.value.question = false;

      // 获取试卷数量
      try {
        const paperResponse = await getPaperList({ userId });
        if (paperResponse.code === 200) {
          statistics.value.paperCount = paperResponse.data.total || 0;
        }
        // 试卷数据加载完成
        cardLoading.value.paper = false;
      } catch (error) {
        console.error('获取试卷数据失败:', error);
        cardLoading.value.paper = false;
      }

      // 更新统计数据
      statistics.value.knowledgeCount = totalKnowledgeCount;
      chartData.value.knowledgeBySubject = knowledgeBySubject;
      chartData.value.questionsBySubject = questionsBySubject;
      chartData.value.masteryDistribution = masteryData;
      chartData.value.difficultyDistribution = difficultyData;
      chartData.value.monthlyGrowth = monthsData;
      chartData.value.chapterKnowledgeData = chapterKnowledgeData;
      chartData.value.questionTypeData = questionTypeData;

      // 初始化图表
      nextTick(() => {
        initCharts();
        // 所有数据加载完成，关闭全屏加载
        loading.value = false;
      });
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    // 发生错误时也关闭加载状态
    loading.value = false;
    Object.keys(cardLoading.value).forEach(key => {
      cardLoading.value[key] = false;
    });
    Object.keys(chartLoading.value).forEach(key => {
      chartLoading.value[key] = false;
    });
  }
};

// 初始化所有图表
const initCharts = () => {
  initSubjectKnowledgeChart();
  initSubjectQuestionChart();
  initMasteryDistributionChart();
  initDifficultyDistributionChart();
  initKnowledgeGrowthChart();
  
  // 设置默认选中的第一个学科
  if (chartData.value.subjects.length > 0) {
    chapterSelectedSubject.value = chartData.value.subjects[2];
    questionTypeSelectedSubject.value = chartData.value.subjects[2];
    
    // 初始化新增的图表
    initChapterKnowledgeChart();
    initQuestionTypeChart();
  }

  // 添加窗口大小变化事件监听
  window.addEventListener('resize', handleResize);
};

// 图表大小调整处理
const handleResize = () => {
  subjectKnowledgeChart && subjectKnowledgeChart.resize();
  subjectQuestionChart && subjectQuestionChart.resize();
  masteryDistributionChart && masteryDistributionChart.resize();
  difficultyDistributionChart && difficultyDistributionChart.resize();
  knowledgeGrowthChart && knowledgeGrowthChart.resize();
  chapterKnowledgeChart && chapterKnowledgeChart.resize();
  questionTypeChart && questionTypeChart.resize();
};

// 初始化学科知识点饼图
const initSubjectKnowledgeChart = () => {
  const chartDom = document.getElementById('subjectKnowledgeChart');
  if (!chartDom) return;

  subjectKnowledgeChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      type: 'scroll',
      textStyle: {
        fontSize: 12
      }
    },
    series: [
      {
        name: '知识点数量',
        type: 'pie',
        radius: '70%',
        center: ['60%', '50%'],
        data: chartData.value.knowledgeBySubject,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        }
      }
    ]
  };
  
  subjectKnowledgeChart.setOption(option);
  
  // 图表初始化完成后取消加载状态
  chartLoading.value.subjectKnowledge = false;
};

// 初始化学科题目柱状图
const initSubjectQuestionChart = () => {
  const chartDom = document.getElementById('subjectQuestionChart');
  if (!chartDom) return;

  subjectQuestionChart = echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.subjects,
      axisLabel: {
        interval: 0,
        rotate: 30,
        textStyle: {
          fontSize: 12
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '题目数量'
    },
    series: [
      {
        name: '题目数量',
        type: 'bar',
        data: chartData.value.questionsBySubject.map(item => item.value),
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  };
  
  subjectQuestionChart.setOption(option);
  
  // 图表初始化完成后取消加载状态
  chartLoading.value.subjectQuestion = false;
};

// 初始化掌握程度分布图
const initMasteryDistributionChart = () => {
  const chartDom = document.getElementById('masteryDistributionChart');
  if (!chartDom) return;

  masteryDistributionChart = echarts.init(chartDom);
  
  const data = Object.entries(chartData.value.masteryDistribution).map(([name, value]) => ({
    name,
    value
  }));
  
  const colors = ['#91cc75', '#fac858', '#5470c6', '#ee6666', '#73c0de'];
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '掌握程度',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: data,
        color: colors
      }
    ]
  };
  
  masteryDistributionChart.setOption(option);
  
  // 图表初始化完成后取消加载状态
  chartLoading.value.masteryDistribution = false;
};

// 初始化难度系数分布图
const initDifficultyDistributionChart = () => {
  const chartDom = document.getElementById('difficultyDistributionChart');
  if (!chartDom) return;

  difficultyDistributionChart = echarts.init(chartDom);
  
  const data = Object.entries(chartData.value.difficultyDistribution).map(([name, value]) => ({
    name: name === '1' ? '简单' : (name === '2' ? '中等' : '困难'),
    value
  }));
  
  const colors = ['#91cc75', '#fac858', '#ee6666'];
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '难度系数',
        type: 'pie',
        radius: '70%',
        center: ['60%', '50%'],
        data: data,
        color: colors,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        }
      }
    ]
  };
  
  difficultyDistributionChart.setOption(option);
  
  // 图表初始化完成后取消加载状态
  chartLoading.value.difficultyDistribution = false;
};

// 初始化知识点增长趋势图
const initKnowledgeGrowthChart = () => {
  const chartDom = document.getElementById('knowledgeGrowthChart');
  if (!chartDom) return;

  knowledgeGrowthChart = echarts.init(chartDom);
  
  const months = chartData.value.monthlyGrowth.map(item => item.month);
  const counts = chartData.value.monthlyGrowth.map(item => item.count);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: months,
      axisLabel: {
        formatter: function(value) {
          return value.slice(5); // 只显示月份
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '知识点数量'
    },
    series: [
      {
        name: '新增知识点',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: counts,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#5470c6'
        },
        lineStyle: {
          width: 3
        }
      }
    ]
  };
  
  knowledgeGrowthChart.setOption(option);
};

// 处理章节图表学科选择变化
const handleChapterSubjectChange = () => {
  if (chapterSelectedSubject.value) {
    initChapterKnowledgeChart();
  }
};

// 处理题目类型图表学科选择变化
const handleQuestionTypeSubjectChange = () => {
  if (questionTypeSelectedSubject.value) {
    initQuestionTypeChart();
  }
};

// 初始化章节知识点分布图表
const initChapterKnowledgeChart = () => {
  if (!chapterSelectedSubject.value) return;
  
  // 开始加载
  chartLoading.value.chapterKnowledge = true;
  
  const chartDom = document.getElementById('chapterKnowledgeChart');
  if (!chartDom) return;
  
  // 销毁之前的图表实例
  if (chapterKnowledgeChart) {
    chapterKnowledgeChart.dispose();
  }
  
  chapterKnowledgeChart = echarts.init(chartDom);
  
  const subjectData = chartData.value.chapterKnowledgeData[chapterSelectedSubject.value] || [];
  const chartOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['知识点数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: subjectData.map(item => `第${item.chapter}章`),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '知识点数量'
    },
    series: [
      {
        name: '知识点数量',
        type: 'bar',
        data: subjectData.map(item => item.count),
        itemStyle: {
          color: function(params) {
            // 颜色数组
            const colorList = [
              '#5470c6', '#91cc75', '#fac858', '#ee6666', 
              '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
            ];
            return colorList[params.dataIndex % colorList.length];
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}'
        }
      }
    ]
  };
  
  chapterKnowledgeChart.setOption(chartOption);
  
  // 图表初始化完成后取消加载状态
  chartLoading.value.chapterKnowledge = false;
};

// 初始化题目类型分布图表
const initQuestionTypeChart = () => {
  if (!questionTypeSelectedSubject.value) return;
  
  // 开始加载
  chartLoading.value.questionType = true;
  
  const chartDom = document.getElementById('questionTypeChart');
  if (!chartDom) return;
  
  // 销毁之前的图表实例
  if (questionTypeChart) {
    questionTypeChart.dispose();
  }
  
  questionTypeChart = echarts.init(chartDom);
  
  const subjectData = chartData.value.questionTypeData[questionTypeSelectedSubject.value] || [];
  
  // 题型配置
  const questionTypeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'READING': '阅读理解'
  };
  
  // 题型颜色
  const colorMap = {
    'SINGLE_CHOICE': '#5470c6',
    'MULTIPLE_CHOICE': '#91cc75',
    'TRUE_FALSE': '#fac858',
    'FILL_BLANK': '#ee6666',
    'SHORT_ANSWER': '#73c0de',
    'READING': '#3ba272'
  };
  
  // 饼图数据
  const pieData = Object.entries(subjectData).map(([type, count]) => ({
    name: questionTypeMap[type] || type,
    value: count,
    itemStyle: {
      color: colorMap[type]
    }
  }));
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '题目类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        data: pieData
      }
    ]
  };
  
  questionTypeChart.setOption(option);
  
  // 图表初始化完成后取消加载状态
  chartLoading.value.questionType = false;
};

// 组件挂载时初始化
onMounted(() => {
  initStatistics();
});

// 组件卸载时清理资源
onUnmounted(() => {
  // 移除窗口大小变化事件监听
  window.removeEventListener('resize', handleResize);
  
  // 销毁所有图表实例
  subjectKnowledgeChart && subjectKnowledgeChart.dispose();
  subjectQuestionChart && subjectQuestionChart.dispose();
  masteryDistributionChart && masteryDistributionChart.dispose();
  difficultyDistributionChart && difficultyDistributionChart.dispose();
  knowledgeGrowthChart && knowledgeGrowthChart.dispose();
  chapterKnowledgeChart && chapterKnowledgeChart.dispose();
  questionTypeChart && questionTypeChart.dispose();
});
</script>

<style scoped>
.statistics-view {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  position: relative;
}

/* 卡片加载动画 */
.shimmer-effect {
  position: relative;
  overflow: hidden;
}

.shimmer-effect::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: linear-gradient(
    90deg, 
    rgba(255, 255, 255, 0) 0%, 
    rgba(255, 255, 255, 0.6) 50%, 
    rgba(255, 255, 255, 0) 100%
  );
  animation: shimmer 2s infinite;
}

.top-header {
  margin-bottom: 24px;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

/* 统计卡片样式 */
.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
}

.card-header {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 16px;
}

.card-header .el-icon {
  margin-right: 8px;
  font-size: 18px;
}

.card-content {
  text-align: center;
  padding: 10px 0;
}

.card-content h3 {
  font-size: 28px;
  color: #409EFF;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.card-content p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

/* 图表卡片样式 */
.chart-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

/* 图表标题区样式 */
.chart-card .card-header {
  justify-content: space-between;
  padding: 15px 20px;
  display: flex;
  align-items: center;
}

.chart-card .header-actions {
  display: flex;
  align-items: center;
}

.chart-card .header-actions .el-select {
  width: 150px;
  margin-left: 16px;
}

/* 空数据和加载样式 */
.chart-empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.chart-empty-data .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #DCDFE6;
}

.chart-empty-data .empty-text {
  font-size: 14px;
}

.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
}

.el-loading-spinner .path {
  stroke: #409EFF;
}

.chart-card .el-loading-spinner .el-loading-text {
  color: #409EFF;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .chart-container {
    height: 300px;
  }
  
  .chart-container-wrapper {
    height: 300px;
  }
  
  .pie-placeholder,
  .donut-placeholder {
    width: 150px;
    height: 150px;
  }
  
  .donut-placeholder::before {
    width: 90px;
    height: 90px;
  }
  
  .donut-skeleton-large .donut-placeholder {
    width: 180px;
    height: 180px;
  }
  
  .donut-skeleton-large .donut-placeholder::before {
    width: 100px;
    height: 100px;
  }
}

@media (max-width: 768px) {
  .stat-cards .el-col {
    margin-bottom: 20px;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .chart-container-wrapper {
    height: 250px;
  }
  
  .chart-section .el-col {
    margin-bottom: 20px;
  }
  
  .bar-item {
    width: 25px;
  }
  
  .bar-skeleton-wide .bar-item {
    width: 35px;
  }
  
  .pie-placeholder,
  .donut-placeholder {
    width: 120px;
    height: 120px;
  }
  
  .donut-placeholder::before {
    width: 70px;
    height: 70px;
  }
  
  .legend-placeholder {
    width: 80px;
  }
}

/* 图表骨架屏样式 */
.chart-skeleton {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  background-color: rgba(255, 255, 255, 0.5);
  padding: 20px;
}

.invisible {
  visibility: hidden;
}

/* 饼图骨架样式 */
.pie-skeleton {
  justify-content: space-between;
}

.pie-placeholder {
  width: 200px;
  height: 200px;
  background: linear-gradient(90deg, #f0f2f5 0%, #e5e9f2 100%);
  border-radius: 50%;
  position: relative;
  overflow: hidden;
  animation: pulse 1.5s infinite ease-in-out;
}

.pie-placeholder::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: conic-gradient(
    #e6f7ff 0deg 60deg,
    #d9f2e6 60deg 150deg,
    #fff7e6 150deg 230deg,
    #fde2e2 230deg 360deg
  );
  opacity: 0.8;
  border-radius: 50%;
  animation: rotating 3s linear infinite;
}

/* 环形图骨架样式 */
.donut-skeleton {
  justify-content: space-between;
}

.donut-placeholder {
  width: 200px;
  height: 200px;
  background: #f0f2f5;
  border-radius: 50%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  animation: pulse 1.5s infinite ease-in-out;
}

.donut-placeholder::before {
  content: '';
  position: absolute;
  width: 120px;
  height: 120px;
  background-color: white;
  border-radius: 50%;
  z-index: 1;
}

.donut-placeholder::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: conic-gradient(
    #5470c6 0deg 80deg,
    #91cc75 80deg 140deg,
    #fac858 140deg 200deg,
    #ee6666 200deg 260deg,
    #73c0de 260deg 360deg
  );
  border-radius: 50%;
  animation: rotating 3s linear infinite;
}

.donut-skeleton-large .donut-placeholder {
  width: 250px;
  height: 250px;
}

.donut-skeleton-large .donut-placeholder::before {
  width: 150px;
  height: 150px;
}

.legend-placeholder {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-left: 20px;
  width: 120px;
}

.legend-item {
  height: 15px;
  background: linear-gradient(90deg, #f0f2f5, #e5e9f2);
  border-radius: 3px;
  animation: pulse 1.5s infinite ease-in-out;
  animation-delay: calc(0.1s * var(--i, 0));
}

.legend-item:nth-child(1) { --i: 1; width: 80%; }
.legend-item:nth-child(2) { --i: 2; width: 70%; }
.legend-item:nth-child(3) { --i: 3; width: 90%; }
.legend-item:nth-child(4) { --i: 4; width: 60%; }
.legend-item:nth-child(5) { --i: 5; width: 75%; }
.legend-item:nth-child(6) { --i: 6; width: 85%; }

/* 柱状图骨架样式 */
.bar-skeleton {
  display: flex;
  align-items: flex-end;
  justify-content: space-around;
  height: 100%;
  padding-bottom: 60px;
  box-sizing: border-box;
}

.bar-item {
  width: 40px;
  background: linear-gradient(0deg, #e6f7ff, #bae7ff);
  border-radius: 3px 3px 0 0;
  animation: growUp 1.5s infinite ease-in-out alternate;
}

.bar-item:nth-child(1) { height: 60%; animation-delay: 0.1s; }
.bar-item:nth-child(2) { height: 80%; animation-delay: 0.2s; }
.bar-item:nth-child(3) { height: 45%; animation-delay: 0.3s; }
.bar-item:nth-child(4) { height: 70%; animation-delay: 0.4s; }
.bar-item:nth-child(5) { height: 55%; animation-delay: 0.5s; }
.bar-item:nth-child(6) { height: 65%; animation-delay: 0.6s; }
.bar-item:nth-child(7) { height: 75%; animation-delay: 0.7s; }
.bar-item:nth-child(8) { height: 50%; animation-delay: 0.8s; }

.bar-skeleton-wide .bar-item {
  width: 60px;
}

/* 动画关键帧 */
@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 0.6;
  }
  50% {
    opacity: 0.9;
  }
}

@keyframes growUp {
  from {
    opacity: 0.6;
    transform: scaleY(0.8);
  }
  to {
    opacity: 0.9;
    transform: scaleY(1);
  }
}

/* 图表容器样式 */
.chart-container-wrapper {
  position: relative;
  height: 350px;
}

/* 动画关键帧 */
@keyframes shimmer {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}
</style> 